using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;

namespace ZhiSe.Editor
{
    public static class SeegUtil
    {

        private static void MoveOldDir()
        {
            var oldDir = Path.Combine(Application.dataPath, "Seeg/Editor/Resources");
            if (!Directory.Exists(oldDir))
            {
                return;
            }
            // 遍历文件
            var dirs = Directory.GetDirectories(oldDir);
            foreach (var dir in dirs)
            {
                var newDir = dir.Replace("Resources", "cfg");
                if (!Directory.Exists(newDir))
                {
                    Directory.CreateDirectory(newDir);
                }
                var files = Directory.GetFiles(dir);
                foreach (var file in files)
                {
                    var newFile = file.Replace("Resources", "cfg");
                    if (File.Exists(newFile) || file.EndsWith(".meta"))
                    {
                        File.Delete(file);
                        continue;
                    }
                    File.Move(file, newFile);
                }
                Directory.Delete(dir);
            }
            var oldFiles = Directory.GetFiles(oldDir);
            foreach (var file in oldFiles)
            {
                var newFile = file.Replace("Resources", "cfg");
                if (File.Exists(newFile) || file.EndsWith(".meta"))
                {
                    File.Delete(file);
                    continue;
                }
                File.Move(file, newFile);
            }
            Directory.Delete(oldDir);
            var oldMeta = Path.Combine(Application.dataPath, "Seeg/Editor/Resources.meta");
            if (File.Exists(oldMeta))
            {
                File.Delete(oldMeta);
            }
        }

        public static string GetCfgDir()
        {
            var cfgDir = Path.Combine(Application.dataPath, "Seeg/Editor/Cfg");
            if (!Directory.Exists(cfgDir))
            {
                Directory.CreateDirectory(cfgDir);
            }
            // 判断老文件
            MoveOldDir();
            return cfgDir;
        }

        private static string GetSdkCfgPath()
        {
            return Path.Combine(GetCfgDir(), "sdk_config.json");
        }
        
        public static JObject GetSdkCfg()
        {

            var configPath = GetSdkCfgPath();
            if (!File.Exists(configPath))
            {
                Debug.LogWarning("[SEEG] SeegSDK构建配置文件不存在");
                return null;
            }
            var json = File.ReadAllText(configPath);
            if (string.IsNullOrEmpty(json))
            {
                Debug.LogWarning("[SEEG] SeegSDK构建配置为空");
                return null;
            }
            var sdkParam = JObject.Parse(json);
            var gid = sdkParam.Value<string>("current") ?? "";
            var info = sdkParam.Value<JObject>("info");
            return info?.Value<JObject>(gid);
        }
    }

    public class SeegEditorWindow : EditorWindow
    {
        private readonly string[] _marcos = new[]
        {
            "SEEG_PF_WX",
            "SEEG_PF_TT",
            "SEEG_PF_KS",
            "SEEG_PF_WEB",
            "SEEG_PF_GP",
            "SEEG_PF_IOS"
        };
        
        private List<string> _gidList;
        
        private JObject _sdkParam;
        
        private int _gidIdx;
        private int _lastIdx = -1;

        private string _gid;
        private string _version;
        private bool _debug;
        private int _loggerLevel;
        private string _tdAppKey;
        private bool  _jumpWechat;
        private bool  _reportSs;
        private bool _onlyWeb;
        private int _ksBuildTime;
        private bool _podInstall;
        
        private Vector2 _scrollPos;
        
        [MenuItem("SeegSdk/设置面板", false, 1)]
        public static void Open()
        {
            var window = GetWindow(typeof(SeegEditorWindow), true, "指色SDK设置面板");
            window.Show();
        }

        private void OnGUI()
        {
            _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos);
            DealConfig();
            EditorGUILayout.EndScrollView();
        }

        private void DealConfig()
        {
            if (null == _gidList || null == _sdkParam)
            {
                var sdkParamPath = $"{SeegUtil.GetCfgDir()}/sdk_config.json";
                if (!File.Exists(sdkParamPath))
                {
                    _sdkParam = new JObject();
                }
                else
                {
                    var json = File.ReadAllText(sdkParamPath);
                    _sdkParam = string.IsNullOrEmpty(json) ? new JObject() : JObject.Parse(json);
                }

                _gidList = new List<string>
                {
                    "新增"
                };
                var tempInfo = _sdkParam.Value<JObject>("info");
                if (null == tempInfo)
                {
                    _sdkParam["info"] = new JObject();
                }
                else
                {
                    foreach (var param in tempInfo)
                    {
                        _gidList.Add(param.Key);
                    }
                }
                var temp = _sdkParam.Value<string>("current");
                if (!string.IsNullOrEmpty(temp) && _gidList.Contains(temp))
                {
                    _gidIdx = _gidList.IndexOf(temp);
                }
            }

            _gidIdx = EditorGUILayout.Popup("选择", _gidIdx, _gidList.ToArray());
            if (_gidIdx == 0)
            {
                EditorGUILayout.HelpBox("GID一般以平台开头，非AppId", MessageType.Info, true);
                _gid = EditorGUILayout.TextField("GID(游戏标识)", _gid);
            }
            else
            {
                _gid = _gidList[_gidIdx];
            }
            if (_lastIdx != _gidIdx)
            {
                if (_gidIdx == 0)
                {
                    _gid = "";
                    _version = "1.0.0";
                    _debug = false;
                    _loggerLevel = 0;
                    _tdAppKey = "";
                    _jumpWechat = false;
                    _reportSs = false;
                    _onlyWeb = false;
                    _ksBuildTime = 5;
                }
                else
                {
                    var info =  _sdkParam.Value<JObject>("info")!.Value<JObject>(_gid);
                    _gid = info.Value<string>("gid");
                    _version = info.Value<string>("version") ?? "1.0.0";
                    _debug = info.Value<bool>("debug");
                    _loggerLevel = info.Value<int>("loggerLevel");
                    _tdAppKey = info.Value<string>("tdAppKey");
                    _jumpWechat = info.Value<bool>("jumpWX");
                    _reportSs = info.Value<bool>("reportSS");
                    _onlyWeb = info.Value<bool>("onlyWeb");
                    _podInstall = info.Value<bool>("podInstall");
                    var ksBuildTime = info.Value<int>("ksBuildTime");
                    _ksBuildTime = ksBuildTime == 0 ? 5 : ksBuildTime;
                }

                _lastIdx = _gidIdx;
            }

            if (_gid.Contains("_"))
            {
                if (!_gid.EndsWith("_"))
                {
                    EditorGUILayout.HelpBox("读取后台配置的版本号，无特别说明，默认1.0.0即可", MessageType.Info, true);
                    _version = EditorGUILayout.TextField("配置版本", _version);
                }
                EditorGUILayout.HelpBox("调试模式，切勿随意开启，需要建立专门的测试通道才可使用", MessageType.Info, true);
                _debug = EditorGUILayout.Toggle("调试模式", _debug);
                EditorGUILayout.HelpBox("可选0-5，0为关闭，5全开", MessageType.Info, true);
                _loggerLevel = EditorGUILayout.IntField("日志等级", _loggerLevel);
            }
            
            var isAndroid = _gid.StartsWith("hgg_");
            var isIOS = _gid.StartsWith("hios_");
            var isNative = isAndroid || isIOS;
            
            var isWx = _gid.StartsWith("wx_");
            var isKs = _gid.StartsWith("ks_");
            var isTt =_gid.StartsWith("tt_");
            var isMiniGame = isWx || isKs || isTt;
            
            // 获取Unity当前的平台
            var group = BuildTargetGroup.Unknown;
            var target = BuildTarget.StandaloneWindows;
            var currentPlatform = EditorUserBuildSettings.selectedBuildTargetGroup;
            if (isAndroid)
            {
                group = BuildTargetGroup.Android;
                target = BuildTarget.Android;
            } 
            else if (isIOS)
            {
                group = BuildTargetGroup.iOS;
                target = BuildTarget.iOS;
            }
            else if (isMiniGame)
            {
                
#if TUANJIE_1_0_OR_NEWER
                group = BuildTargetGroup.MiniGame;
                target = BuildTarget.MiniGame;
#else
                group = BuildTargetGroup.WebGL;
                target = BuildTarget.WebGL;
#endif
                
            }
            
            if (group != BuildTargetGroup.Unknown && currentPlatform != BuildTargetGroup.Standalone && group != currentPlatform)
            {
                if (DeleteGid())
                {
                    return;
                }
                
                EditorGUILayout.HelpBox($"GID平台为{group}，当前平台为{currentPlatform}，需要切换平台，切换后需要打开一次构建面板", MessageType.Warning, true);
                if (!GUILayout.Button("切换平台")) return;
                // 切换平台
                EditorUserBuildSettings.SwitchActiveBuildTargetAsync(group, target);
                return;
            }
            
            if (isNative)
            {
                PlayerSettings.productName = EditorGUILayout.TextField("应用名", PlayerSettings.productName);
                if (currentPlatform == group)
                {
                    var applicationIdentifier = EditorGUILayout.TextField("应用包名", PlayerSettings.applicationIdentifier);
                    if (PlayerSettings.applicationIdentifier != applicationIdentifier)
                    {
                        PlayerSettings.SetApplicationIdentifier( group, applicationIdentifier );
                    }
                }
                PlayerSettings.bundleVersion = EditorGUILayout.TextField("版本名称", PlayerSettings.bundleVersion);
                if (isAndroid)
                {
                    EditorGUILayout.HelpBox("提审后，下次打包需要提升版本号", MessageType.Info, true);
                    PlayerSettings.Android.bundleVersionCode = EditorGUILayout.IntField("版本号", PlayerSettings.Android.bundleVersionCode);
                } 
                else
                {
                    PlayerSettings.iOS.buildNumber = EditorGUILayout.TextField("版本号", PlayerSettings.iOS.buildNumber);
                    EditorGUILayout.HelpBox("第一次pod时间过长，可以自行执行pod命令", MessageType.Info, true);
                    _podInstall = EditorGUILayout.Toggle("执行pod", _podInstall);
                }
            } 
            else
            {
                if (isWx)
                {
                    EditorGUILayout.HelpBox("抖跳微、快跳微，请开启，开启后自动添加小游戏官方插件", MessageType.Info, true);
                    _jumpWechat = EditorGUILayout.Toggle("外部跳微", _jumpWechat);
                }
            
                if (isKs)
                {
                    _ksBuildTime = EditorGUILayout.IntField("快手构建时间", _ksBuildTime);
                }
            
                if (isMiniGame)
                {
                    EditorGUILayout.HelpBox("TD统计集成，如提供该参数则填写", MessageType.Info, true);
                    _tdAppKey = EditorGUILayout.TextField("tdAppKey(TalkingData)", _tdAppKey);
                    EditorGUILayout.HelpBox("数数统计集成，根据运营需要选择", MessageType.Info, true);
                    _reportSs = EditorGUILayout.Toggle("数数打点", _reportSs);
                    EditorGUILayout.HelpBox("仅构建WEB包时打开(如集成了官方导出插件，可关闭)，构建小游戏正式包请关闭", MessageType.Info, true);
                    _onlyWeb = EditorGUILayout.Toggle("仅构建WEB", _onlyWeb);
                }
                
            }
            
            if (DeleteGid())
            {
                return;
            }

            if (string.IsNullOrEmpty(_gid))
            {
                return;
            }
            
            if (!GUILayout.Button("保存")) return;

            if (_gid.Contains(" "))
            {
                EditorUtility.DisplayDialog("参数填写错误", "gid存在空格，请检查", "确定");
                return;
            }

            var pf = _gid.Split('_')[0];
            var macro = pf switch
            {
                "wx" => "SEEG_PF_WX",
                "tt" => "SEEG_PF_TT",
                "ks" => "SEEG_PF_KS",
                "hgg" => "SEEG_PF_GP",
                "hios" => "SEEG_PF_APPSTORE",
                _ => ""
            };

            if (string.IsNullOrEmpty(macro))
            {
                Debug.LogError("[SEEG] 输入的gid不对");
                return;
            }

            if (_onlyWeb)
            {
                macro = "SEEG_PF_WEB";
            }
            
            var infoParam = (JObject)_sdkParam["info"];
            if (!infoParam.ContainsKey(_gid))
            {
                _gidList.Add(_gid);
            }

            infoParam[_gid] = new JObject
            {
                { "gid", _gid },
                { "version", _version },
                { "debug", _debug },
                { "loggerLevel", _loggerLevel },
                { "tdAppKey", _tdAppKey },
                { "jumpWX", _jumpWechat },
                { "reportSS", _reportSs },
                { "ksBuildTime", _ksBuildTime},
                { "podInstall", _podInstall}
            };
            _sdkParam["current"] = _gid;
            var gidParam = (JObject)infoParam[_gid];
            if (!isIOS)
            {
                gidParam.Remove("podInstall");
            }
            if (!isWx)
            {
                gidParam.Remove("jumpWX");
            }
            if (!isKs)
            {
                gidParam.Remove("ksBuildTime");
            }
            if (!isMiniGame)
            {
                gidParam.Remove("tdAppKey");
                gidParam.Remove("reportSS");
            }
            
            // 获取宏配置
            var defineSymbolsGroup =
                PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
            var defineList = defineSymbolsGroup.Split(';').ToList();
            var hasChange = false;
            if (!defineList.Contains(macro))
            {
                hasChange = true;
                defineList.Add(macro);
            }
            for (var i = defineList.Count - 1; i >= 0; i--) 
            {
                if (defineList[i] == macro)
                {
                    continue;
                }
                if (!_marcos.Contains(defineList[i])) continue;
                hasChange = true;
                defineList.RemoveAt(i);
            }

            if (hasChange)
            {
                PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", defineList));
            }
            
            // 保存配置
            File.WriteAllText($"{SeegUtil.GetCfgDir()}/sdk_config.json", _sdkParam.ToString(Formatting.None));

            if (isWx)
            {
                var wxPluginDir = Path.Combine(Application.dataPath, "Seeg/Editor/Wechat");
                var wxPluginPath = Path.Combine(wxPluginDir, "SeegWXPlugin.cs");
                if (!Directory.Exists(wxPluginPath))
                {
                    Directory.CreateDirectory(wxPluginDir);
                    var text = new[]
                    {
                        "#if UNITY_WEBGL && SEEG_PF_WX",
                        "namespace ZhiSe.Editor",
                        "{",
                        "   public class SeegWXPlugin: WeChatWASM.LifeCycleBase",
                        "   {",
                        "       public override void afterBuildTemplate()",
                        "       {",
                        "           UnityEngine.Debug.Log(\"[SEEG] WeChatWASM.LifeCycleBase->afterBuildTemplate\");",
                        "           SeegWXBuild.afterBuildTemplate();",
                        "       }",
                        "   }",
                        "}",
                        "#endif"
                    };
                    File.WriteAllLines(wxPluginPath, text);
                    // 刷新unity资源
                    AssetDatabase.Refresh();
                }
            }

            Debug.Log("[SEEG] 保存完毕");
        }

        private bool DeleteGid()
        {
            if (!GUILayout.Button("删除"))
            {
                return false;
            }
            if (_gidIdx == 0)
            {
                Debug.LogError("[SEEG] 当前数据并未保存");
                return false;
            }
            _gidList.RemoveAt(_gidIdx);
            ((JObject)_sdkParam["info"])?.Remove(_gid);
            _gidIdx = 0;
            File.WriteAllText($"{SeegUtil.GetCfgDir()}/sdk_config.json", _sdkParam.ToString(Formatting.None));
            return true;
        }

        private void OnFocus()
        {
            Debug.Log("[SEEG] 打开配置面板");
        }

        private void OnDestroy()
        {
            Debug.Log("[SEEG] 退出配置面板");
        }
    }
}